<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <el-form :inline="true" :model="selFunctionListQuery">
          <el-form-item label="功能名称">
            <el-input
              v-model="selFunctionListQuery.name"
              clearable
              placeholder="请输入功能名称"
            />
          </el-form-item>
          <!-- <el-form-item label="功能别名">
            <el-input
              clearable
              v-model="queryParams.functionAlias"
              placeholder="请输入功能别名"
            ></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-collapse-transition>
    <el-card>
      <!-- <div slot="header"></div> -->
      <div>
        <!-- 操作按钮区域 -->
        <div class="table-operations">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            />
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >新建</el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="handleBatchDelete"
          >批量删除</el-button>
        </div>

        <!-- 表格区域 -->
        <el-table
          v-loading="loading"
          :data="selFunctionLists"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            type="index"
            label="序号"
            width="60"
          />
          <el-table-column
            prop="name"
            label="功能名称"
            align="center"
          />
          <el-table-column
            prop="byName"
            label="功能标识"
            align="center"
          />
          <!-- <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            width="180"
          >
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column> -->
          <!-- <el-table-column
            prop="updateTime"
            label="更新时间"
            align="center"
            width="180"
          >
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.updateTime) }}
            </template>
          </el-table-column> -->

          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
        <el-pagination
          background
          :current-page="selFunctionListQuery.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="selFunctionListQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="addFunctionQuery.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="addFunctionQuery"
        :rules="rules"
        label-width="100px"
      >
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="编号:" prop="number">
              <el-input
                v-model="addFunctionQuery.number"
                placeholder="请输入编号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row>
          <el-col :span="24">
            <el-form-item label="功能名称:" prop="name">
              <el-input
                v-model="addFunctionQuery.name"
                placeholder="请输入功能名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="英文名称:" prop="sign">
              <el-input
                v-model="addFunctionQuery.sign"
                placeholder="请输入英文名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input
                v-model="addFunctionQuery.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selFunctionListApi,
  addFunctionApi,
  updateFunctionByIdApi,
  delFunctionByIdApi
} from '@/api/system'

export default {
  name: 'UserManagement',
  data() {
    return {
      // 添加搜索框显示状态
      showSearch: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: '',
        accountName: '',
        department: ''
      },
      // 表格数据
      tableData: [
        {
          accountName: '管理员',
          loginAccount: 'TVAdmin',
          role: '超级管理员',
          department: '',
          updateTime: '2025-01-21',
          createTime: '2017-04-06'
        },
        {
          accountName: '普通用户',
          loginAccount: 'user',
          role: '法律顾问',
          department: '行政中心',
          updateTime: '2024-10-18',
          createTime: '2022-10-27'
        }
      ],
      // 功能管理列表
      selFunctionLists: [],
      isFilterVisible: false,
      // 总条数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 表单对象
      form: {
        accountName: '',
        loginAccount: '',
        role: '',
        department: ''
      },
      // 表单对象 - 根据接口文档调整字段
      addFunctionQuery: {
        name: '', // 功能名称
        number: '', // 编号
        sign: '' // 功能标识
      },
      // 功能管理查询参数
      selFunctionListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      // 表单校验规则 - 根据接口文档调整校验
      rules: {
        name: [
          { required: true, message: '请输入功能名称', trigger: 'blur' },
          { type: 'string', message: '功能名称必须为字符串', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入编号', trigger: 'blur' },
          { type: 'number', message: '编号必须为数字', trigger: 'blur' }
        ],
        sign: [
          { required: true, message: '请输入功能标识', trigger: 'blur' },
          { type: 'string', message: '功能标识必须为字符串', trigger: 'blur' }
        ]
      },
      selectedIds: [] // 选中项的 id 数组
    }
  },
  created() {
    this.selFunctionList()
  },
  methods: {
    // 切换搜索框显示状态
    // toggleSearch() {
    //   this.showSearch = !this.showSearch;
    // },
    // 功能管理列表
    async selFunctionList() {
      const res = await selFunctionListApi(this.selFunctionListQuery)
      console.log(res)
      this.selFunctionLists = res.records
      this.total = res.total
    },
    // 查询按钮点击事件
    handleQuery() {
      this.selFunctionListQuery.page = 1
      this.selFunctionList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.selFunctionListQuery = {
        page: 1,
        pageSize: 10,
        name: ''
      }
      this.selFunctionList()
    },
    // 获取最大编号
    getMaxNumber() {
      if (!this.selFunctionLists || this.selFunctionLists.length === 0) {
        return 1
      }
      const maxNumber = Math.max(
        ...this.selFunctionLists.map((item) => Number(item.number) || 0)
      )
      return maxNumber + 1
    },

    // 新增按钮点击事件
    handleAdd() {
      this.dialogVisible = true
      this.resetForm()
      this.addFunctionQuery.number = this.getMaxNumber()
    },

    // 编辑按钮点击事件 - 调整提取的字段
    handleEdit(row) {
      this.dialogVisible = true
      this.addFunctionQuery = {
        id: row.id,
        name: row.name,
        number: row.number,
        sign: row.sign
      }
    },

    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认删除该功能吗？', '提示', {
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await delFunctionByIdApi([row.id])
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.selFunctionList()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败，请重试')
          }
        })
        .catch(() => {})
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的功能')
        return
      }

      this.$confirm('确定要删除选中的功能吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await delFunctionByIdApi(this.selectedIds)
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.selectedIds = []
              this.selFunctionList()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败，请重试')
          }
        })
        .catch(() => {})
    },

    // 表格多选变化
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id)
    },

    // 提交表单 - 调整提交的数据
    handleSubmit() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          try {
            const submitData = {
              ...this.addFunctionQuery,
              number: Number(this.addFunctionQuery.number) // 确保 number 为数字类型
            }

            let res
            if (submitData.id) {
              res = await updateFunctionByIdApi(submitData)
            } else {
              res = await addFunctionApi(submitData)
            }

            if (res.code === 1) {
              this.$message.success(submitData.id ? '编辑成功' : '新增成功')
              this.dialogVisible = false
              this.resetForm()
              this.selFunctionList()
            } else {
              this.$message.error(
                res.msg || (submitData.id ? '编辑失败' : '新增失败')
              )
            }
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败，请重试')
          }
        }
      })
    },

    // 重置表单 - 调整重置的字段
    resetForm() {
      this.addFunctionQuery = {
        name: '',
        number: '',
        sign: ''
      }
      this.$refs.formRef && this.$refs.formRef.resetFields()
    },

    // 关闭弹窗
    handleDialogClose() {
      this.resetForm()
    },

    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.selFunctionListQuery.pageSize = val
      this.selFunctionList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.selFunctionListQuery.page = val
      this.selFunctionList()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
/* .demo-form-inline {
  display: flex;
  justify-content: space-between;
} */
.search-wrapper {
  margin-bottom: 16px;
}

/* 添加过渡动画样式 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

.table-operations {
  margin-bottom: 16px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 8px;
}

.el-button--text {
  padding: 0 8px;
}
</style>
